/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.emp.solbrillante.sales.view;

import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import pe.emp.solbrillante.sale.Main;

/**
 *
 * @author Ronald
 */
public class JDetallePedido extends javax.swing.JDialog {

    /**
     * Creates new form JDetallePedido
     */
    
    private int idPedido;
    JPedido padre;
    
    public JDetallePedido(java.awt.Frame parent, boolean modal, int idp) {        
        super(parent, modal);
        this.idPedido = idp;
        initComponents(); 
        
                 //pintamos el fondo de la ventana
        ((JFondo)jventana).setImagen("fondo_subVentanal_II.jpg");
        
        
              ((JFondo)jtitulo).setImagen("BarraHorizontalTitulos.png");
        ((JFondo)jsubtitulo).setImagen("BarraHorizontalTitulosBlanco.png");
        
        String idPedidoS = ""+idp+"";
        this.jLabelIdPed.setText(idPedidoS);
        
        llenarcabecera(Integer.parseInt(idPedidoS));
        
        MostarDetallePedido();
    }
  /* creamos este metodo para poder recibir como obejto ala ventana  JPedido
     para poder usar su metodo de  MostrarPedidos
  */ 
   public void setPadre(JPedido padre){
      this.padre = padre;
   }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    
                                                             
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jventana = new JFondo();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableDetallePedido = new javax.swing.JTable();
        jButtonActualizaEntregados = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jtitulo = new JFondo();
        jLabel3 = new javax.swing.JLabel();
        jsubtitulo = new JFondo();
        jLabel1 = new javax.swing.JLabel();
        jLabelIdPed = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Detalle Pedido a Proveedor");
        setMaximumSize(new java.awt.Dimension(850, 550));
        setMinimumSize(new java.awt.Dimension(850, 550));
        setPreferredSize(new java.awt.Dimension(850, 550));

        jventana.setMaximumSize(new java.awt.Dimension(800, 500));
        jventana.setMinimumSize(new java.awt.Dimension(800, 500));
        jventana.setPreferredSize(new java.awt.Dimension(800, 500));

        jTableDetallePedido.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTableDetallePedido.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTableDetallePedidoKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTableDetallePedido);

        jButtonActualizaEntregados.setText("Actualizar Entregados");
        jButtonActualizaEntregados.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonActualizaEntregadosActionPerformed(evt);
            }
        });

        jtitulo.setMaximumSize(new java.awt.Dimension(267, 39));
        jtitulo.setMinimumSize(new java.awt.Dimension(267, 39));
        jtitulo.setPreferredSize(new java.awt.Dimension(267, 39));

        jLabel3.setText("Revisión de Pedido");

        javax.swing.GroupLayout jtituloLayout = new javax.swing.GroupLayout(jtitulo);
        jtitulo.setLayout(jtituloLayout);
        jtituloLayout.setHorizontalGroup(
            jtituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jtituloLayout.createSequentialGroup()
                .addContainerGap(93, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addGap(84, 84, 84))
        );
        jtituloLayout.setVerticalGroup(
            jtituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jtituloLayout.createSequentialGroup()
                .addContainerGap(14, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addContainerGap())
        );

        jsubtitulo.setMaximumSize(new java.awt.Dimension(267, 39));
        jsubtitulo.setMinimumSize(new java.awt.Dimension(267, 39));
        jsubtitulo.setPreferredSize(new java.awt.Dimension(267, 39));

        jLabel1.setText("Código Pedido :");

        jLabelIdPed.setText("jLabel2");

        javax.swing.GroupLayout jsubtituloLayout = new javax.swing.GroupLayout(jsubtitulo);
        jsubtitulo.setLayout(jsubtituloLayout);
        jsubtituloLayout.setHorizontalGroup(
            jsubtituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jsubtituloLayout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabelIdPed)
                .addContainerGap(117, Short.MAX_VALUE))
        );
        jsubtituloLayout.setVerticalGroup(
            jsubtituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jsubtituloLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jsubtituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabelIdPed))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jventanaLayout = new javax.swing.GroupLayout(jventana);
        jventana.setLayout(jventanaLayout);
        jventanaLayout.setHorizontalGroup(
            jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jventanaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jventanaLayout.createSequentialGroup()
                        .addGroup(jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jsubtitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jventanaLayout.createSequentialGroup()
                        .addGroup(jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jventanaLayout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jButtonActualizaEntregados))
                            .addGroup(jventanaLayout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 809, Short.MAX_VALUE)))
                        .addGap(14, 14, 14))))
        );
        jventanaLayout.setVerticalGroup(
            jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jventanaLayout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jtitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jsubtitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jventanaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jventanaLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addGap(345, 345, 345))
                    .addGroup(jventanaLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonActualizaEntregados)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jventana, javax.swing.GroupLayout.DEFAULT_SIZE, 837, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jventana, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonActualizaEntregadosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonActualizaEntregadosActionPerformed
//        
//        //int col = this.jTableListaPaquetesProveedor.getModel().getColumnCount();
                 int fil = this.jTableDetallePedido.getModel().getRowCount(); 
//                    System.out.println("nro rows : " + fil);
//                    
//                   if ( this.jTextFieldTotalPedido.getText().toString().equals("0")){
//                        System.out.println("SELECCIONE ALGUN PRODUCTO!");
//                       
//                   }
//                   else{
//                       
//                    // guardar registro del pedido:
//                    //1. insertar un registro en la tabla pedido
//                    System.out.println("EL TOTAL:" + Float.parseFloat(this.jTextFieldTotalPedido.getText().toString()));
//                    int indice_nuevo_pedido = Main.myService.queryInsertaPedidoCompra(Float.parseFloat(this.jTextFieldTotalPedido.getText().toString()), "pendiente");                   
//                    System.out.println("RESULTADO INSERT PEDIDO (INDICE):" + indice_nuevo_pedido);
//                    
//                    //2. insertar cada uno de los registros  en la tabla detalle_pedido , aquellos que no tengan subtototal 0        
//                  UPDATE A CADA LINEA DEL PEDIDO 
                    int idcierre = verificar_cierre_pedido(fil);
                    
                    
                 
                    for( int i=0; i<fil; i++)
                    {
                       int codPedido =  Integer.parseInt( jTableDetallePedido.getModel().getValueAt(i, 0).toString() );                       
                       int codPaquete  = Integer.parseInt( jTableDetallePedido.getModel().getValueAt(i, 1).toString() );                       
                       int cantPendiente  = Integer.parseInt( jTableDetallePedido.getModel().getValueAt(i, 4).toString() );                       
              
                       int res_insert_linea_pedido_update = Main.myService.queryUpdateLineaDetallePedido(codPedido,codPaquete,cantPendiente);
                    
                       System.out.println("fin recorrido");
                    
                      }
       
                     if (idcierre==1){
                        JOptionPane.showMessageDialog(null,"HA RECIBIDO TODOS SUS PAQUETES, SE CERRARA EL PEDIDO!");                   
    //                   int idcierre = verificar_cierre_pedido(fil);
                        int res_pedido_update = Main.myService.queryUpdateEstadoPedido(this.getIdPedido(),"Cerrado");
                        
                        
//                        //utilizamos el metodo de la ventana JPedido
//                        padre.MostarPedidos();
//                        // cerramos la ventana
//                        this.dispose();
                     }
        
                   padre.refreshProductTable();
                   this.dispose();

    }//GEN-LAST:event_jButtonActualizaEntregadosActionPerformed

    private void jTableDetallePedidoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableDetallePedidoKeyReleased
       // TODO add your handling code here:
      //  System.out.print("fila : " + this.jTableListaPaquetesProveedorCompra.getEditingRow()+",col : " + this.jTableListaPaquetesProveedorCompra.getEditingColumn());
        
       System.out.println("TECLA: " + evt.getKeyChar());
        
        int iRowEdit = jTableDetallePedido.getEditingRow();        
        int iColEdit = jTableDetallePedido.getEditingColumn();
        
        int colum = jTableDetallePedido.getSelectedColumn();
        int row = jTableDetallePedido.getSelectedRow();
        System.out.println("rc=" + iRowEdit +"cr=" +iColEdit + "st:"+ ",COL:" +colum+ ",ROW:" +row);
        int paq_recibidos_hoy = Integer.parseInt(jTableDetallePedido.getValueAt(row, colum).toString());        
        int paq_pedidos = Integer.parseInt(jTableDetallePedido.getValueAt(row, colum-2).toString());
        int paq_pend = Integer.parseInt(jTableDetallePedido.getValueAt(row, colum-1).toString());
        int paq_pendientes = paq_pend - paq_recibidos_hoy;
        
        jTableDetallePedido.getModel().setValueAt(paq_pendientes, row, colum-1);
        
        //this.jTextFieldTotalPedido.setText(sumaPedido().toString());
    }//GEN-LAST:event_jTableDetallePedidoKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(JDetallePedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(JDetallePedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(JDetallePedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(JDetallePedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the dialog */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            @Override
//            public void run() {
//                JDetallePedido dialog;
//                dialog = new JDetallePedido(new javax.swing.JFrame(), true , idp);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//                    @Override
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonActualizaEntregados;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelIdPed;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableDetallePedido;
    private javax.swing.JPanel jsubtitulo;
    private javax.swing.JPanel jtitulo;
    private javax.swing.JPanel jventana;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the idPedido
     */
    public int getIdPedido() {
        return idPedido;
    }

    /**
     * @param idPedido the idPedido to set
     */
    public void setIdPedido(int idPedido) {
        this.idPedido = idPedido;
    }
    
    private void MostarDetallePedido() {
                  //throw new UnsupportedOperationException("Not yet implemented");
          //Declaramos las clases necesarias para la conexion     
            
            DefaultTableModel modelo;                               
            
            modelo = new DefaultTableModel(){
            boolean[] canEdit = new boolean [] { false, false, false,false, false, false, true};

            @Override
                         public boolean isCellEditable(int rowIndex, int columnIndex) {
                             return canEdit [columnIndex];
                         }

            };
            
            this.jTableDetallePedido.setModel(modelo);            
        
            //Mostrar todos los pedidos (todos los estados)
            ArrayList<Object> t_linea_detalle = Main.myService.queryLineaDetallePedido(this.getIdPedido());                 
    
            modelo.addColumn("Pedido");
            modelo.addColumn("Paquete");
            modelo.addColumn("Producto");
            modelo.addColumn("SubTotal");           
            modelo.addColumn("Paq. Pedidos");   
            modelo.addColumn("Paq. Pendientes");
            modelo.addColumn("Paq. RecibidosHoy");           
                       
            
           System.out.println("size : " + t_linea_detalle.size());
            for (int i = 0; i < t_linea_detalle.size(); i++) {                                           
                modelo.addRow((Object[])t_linea_detalle.get(i));                  
            }                           
           
    }
    
    
     private int verificar_cierre_pedido(int fil) {

                    int cierre=1;
                    for( int i=0; i<fil; i++)
                    {
                      
                       //int cantPedida  = Integer.parseInt( jTableDetallePedido.getModel().getValueAt(i, 3).toString() );                                              
                       int cantPendiente  = Integer.parseInt( jTableDetallePedido.getModel().getValueAt(i, 5).toString() );
                       System.out.println(i + "--"+cantPendiente);
                       if (cantPendiente != 0){
                           cierre = 0;
                       }                                                    
                                  
        
                    }
                    
                    System.out.println("codigo cierre" + cierre);
        return cierre;
   }

    private void llenarcabecera(int parseInt) {
        //throw new UnsupportedOperationException("Not yet implemented");
        
    }
}
